package com.ojoin.trade.common_core.web.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ojoin.trade.common.Constants;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.DownloadUtils;
import com.ojoin.trade.common.utils.FileUploadUtils;
import com.ojoin.trade.common.utils.ImagesUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.MD5;
import com.ojoin.trade.common.web.domain.AjaxUploadResponse;
import com.ojoin.trade.common.web.domain.Result;
import com.ojoin.trade.common.web.domain.Result.Status;
import com.ojoin.trade.common.web.domain.TbUploadFile;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common_core.utils.TradeUtils;

/**
 * ajax文件上传/下载
 */
@Controller
public class AjaxUploadController {

	private static final Logger log = LoggerFactory
			.getLogger(AjaxUploadController.class);


    //最大上传大小 字节为单位
    private long maxSize = FileUploadUtils.defaultMaxSize;
    //允许的文件内容类型
    private String[] allowedExtension = FileUploadUtils.DEFAULT_ALLOWED_EXTENSION;

    @Autowired
    private TbUploadFileService tbUploadFileService;
    
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile(
            HttpServletRequest request, HttpServletResponse response,
            String busiDir,
            String fileType,
            @RequestParam(value = "uploadFile", required = false) MultipartFile file) throws IOException {
    	int joinuserid = TradeUtils.getJoinId();
    	int fileOwnerId=joinuserid;
    	Result result = getUploadFileResult(request, response, busiDir, file, fileOwnerId,String.valueOf(joinuserid),fileType);
    	CommonUtils.sendJOSNResponse(response, result);
    }

    @RequestMapping(value = "/operate/uploadFile", method = RequestMethod.POST)
    public void uploadOperateFile(
            HttpServletRequest request, HttpServletResponse response,
            String busiDir,
            int fileOwnerId,
            String fileType,
            @RequestParam(value = "uploadFile", required = false) MultipartFile file) throws IOException {
    	int joinuserid=TradeUtils.getJoinId();
    	
    	Result result = getUploadFileResult(request, response, busiDir, file, fileOwnerId,String.valueOf(joinuserid),fileType);
    	CommonUtils.sendJOSNResponse(response, result);
    }
    
    private Result getUploadFileResult(HttpServletRequest request,
			HttpServletResponse response, String busiDir, MultipartFile file,
			int fileOwnerId,
			String joinuserid,
			String fileType
    		) throws IOException  {
		Result res = CommonUtils.getPathUploadedFile(request, response, file, busiDir);
        if (Status.ERROR == res.getStatus()) {
            return res;
        }
        String filePath = String.valueOf(res.getMessage());
        String filename = file.getOriginalFilename();
        TbUploadFile uploadFile=new TbUploadFile();
        uploadFile.setDownloadPath(filePath);
        uploadFile.setOriginalName(filename);
        uploadFile.setUploadOperator(joinuserid);
        uploadFile.setIdOfTbMerchantUser(fileOwnerId);
        uploadFile.setFileType(fileType);
        
        tbUploadFileService.insert(uploadFile);
        
        String MD5Key=joinuserid;
        String fileId=String.valueOf(uploadFile.getId());
        String token=null;
		try {
			token = MD5.md5(fileId + MD5Key, Constants.ENCODING);
		} catch (Exception e) {
			throw new BusinessException("MD5 for %s",fileId + MD5Key);
		}
		
        String downloadUrl="/download?id="+fileId+"&token="+token;
        
        return CommonUtils.buildUploadResult(filename, String.valueOf(uploadFile.getId()),downloadUrl);
	}
    
    
    /**
     * 下载
     *
     * @param request
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(
            HttpServletRequest request, HttpServletResponse response, int id,String token) throws Exception{
        Integer joinuserid = TradeUtils.getJoinId();
        
        String MD5Key=String.valueOf(joinuserid);
        String fileId=String.valueOf(id);
        if(CommonUtils.isEmpty(token)||!MD5.verify(fileId + MD5Key, Constants.ENCODING, token)){
            throw new BusinessException("下载标识无效.");
        }
        
        
        TbUploadFile ufile=tbUploadFileService.queryById(id);
    	
    	String download_filepath = ufile.getDownloadPath();
    	String filename = ufile.getOriginalName();
		
		DownloadUtils.download(request, response, FileUploadUtils.getDefaultBaseDir() + File.separator + download_filepath, filename);
		LogUtils.info(log, "%s下载%s",joinuserid,filename);
    }
    
    
    /**
     * @param request
     * @param files
     * @return
     */
    @RequestMapping(value = "ajaxUpload", method = RequestMethod.POST)
    @ResponseBody
    public AjaxUploadResponse ajaxUpload(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "files[]", required = false) MultipartFile[] files) {


        AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse();

        if (ArrayUtils.isEmpty(files)) {
            return ajaxUploadResponse;
        }

        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            long size = file.getSize();

            try {
                String url = FileUploadUtils.upload(request, FileUploadUtils.getDefaultBaseDir(), file, allowedExtension, maxSize, true);
                String deleteURL = "/ajaxUpload/delete?filename=" + URLEncoder.encode(url, Constants.ENCODING);
                if (ImagesUtils.isImage(filename)) {
                    ajaxUploadResponse.add(filename, size, url, url, deleteURL);
                } else {
                    ajaxUploadResponse.add(filename, size, url, deleteURL);
                }
                continue;
            } catch (IOException e) {
                LogUtils.error(log, e,"file upload error");
                ajaxUploadResponse.add(filename, size, "upload.server.error");
                continue;
            } catch (FileUploadBase.FileSizeLimitExceededException e) {
                ajaxUploadResponse.add(filename, size, "upload.exceed.maxSize");
                continue;
            } catch (BusinessException e) {
				LogUtils.error(log, e,"file upload error");
				throw e;
			}
        }
        return ajaxUploadResponse;
    }


    @RequestMapping(value = "ajaxUpload/delete", method = RequestMethod.POST)
    @ResponseBody
    public String ajaxUploadDelete(
            HttpServletRequest request,
            @RequestParam(value = "filename") String filename) throws Exception {

        if (StringUtils.isEmpty(filename) || filename.contains("\\.\\.")) {
            return "";
        }
        filename = URLDecoder.decode(filename, Constants.ENCODING);

        String filePath = FileUploadUtils.extractUploadDir(request) + "/" + filename;

        File file = new File(filePath);
        file.deleteOnExit();

        return "删除成功";
    }
}
